//
// Created by huili on 2022/3/2.
//
#include <stdio.h>
#include <stdlib.h>

#define SIZE 5
#define ERROR -1

typedef struct {
    int num;
    struct SqlList *next;
} *SqlList;

struct SqlList *insertLink(SqlList L, int num, int i);

struct SqlList *delLink(SqlList lTop, int index);

/**
 * 初始链表
 * @param L
 * @return
 */
struct SqlList *initList(SqlList L) {
    L = (SqlList) malloc(sizeof(SqlList));
    L->next = NULL;
    SqlList top;
    top = L;
    int i;
    for (i = 1; i < 6; ++i) {

        L->next = (SqlList) malloc(sizeof(SqlList));
        L->num = i;
        L = L->next; //不能是L->next = L  这样就成了自己又一次指向自己
    }
    L = top;
    return (struct SqlList *) L;
}

int dynamicLian() {
    SqlList L;
    SqlList pList = initList(L);
    SqlList insertNode = insertLink(pList, 7, 3);

    if(!insertNode) return ERROR;
    int i;
//    for (i = 0; i < 6; ++i) {
//        printf("%d\n", insertNode->num);
//        insertNode = insertNode->next;
//    }

//    SqlList delNode = delLink(pList, 3);
//    if (!delNode) return ERROR;
//
    for (i = 0; i < 6; ++i) {
        printf("%d\n", insertNode->num);
        insertNode = insertNode->next;
    }
}

/**
 * 插入链表
 * @param lTop
 * @param num 要插入的数字
 * @param index 要插入的位置
 * @return
 */
struct SqlList *insertLink(SqlList lTop, int num, int index) {
    if (!lTop) return NULL;
    if (index < 1 || index > SIZE) return NULL;
    SqlList top;
    top = lTop;
    SqlList insertNode; //创建要插入的新节点
    insertNode = (SqlList) malloc(sizeof(SqlList)); //为新节点开辟空间
    insertNode->num = num; //把值赋值到新节点中
    insertNode->next = NULL;
    int i;
    for (i = 0; i != ERROR;) {
        if (i == index - 1) {  //如果发现要插入的节点匹配 就直接将新节点插进去
            insertNode->next = lTop->next;
            lTop->next = insertNode;
            i = -1;
        } else {
            lTop = lTop->next;
            i++;
        }
    }
    return top;
}

/**
 * 删除
 * @param lTop
 * @param index 删除的数字的下标
 * @return
 */
struct SqlList *delLink(SqlList lTop, int index) {
    if (!lTop) return NULL;
    if (index < 1 || index > SIZE) return NULL;
    SqlList top;//创建头指针

    top = lTop;
    int i = 0;
    while (i < index -  1) {
        top = top->next;
        ++i;
    }
    if (!(top->next) || i > index - 1)return NULL;

    SqlList delNode;
    delNode = top->next;
    top->next = delNode->next;
    free(delNode);
    return lTop;
}
